package com.bw.test_bluetooth

import android.Manifest
import android.bluetooth.BluetoothDevice
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.RequiresPermission
import androidx.recyclerview.widget.RecyclerView

/**
 * @author ytx
 * @date 2025-10-30 13:35
 * @description
 */
class BlueToothDeviceAdapter(
    val onItemClick:(device:BluetoothDevice)-> Unit
):RecyclerView.Adapter<BlueToothDeviceAdapter.BluetoothViewHolder>() {
    private var bluetoothDevices:MutableList<BluetoothDevice> = mutableListOf()




    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): BluetoothViewHolder {
        val view = LayoutInflater.from(p0.context).inflate(R.layout.item_bluetooth, p0, false)
        return BluetoothViewHolder(view)
    }

    override fun getItemCount(): Int {
        return bluetoothDevices.size
    }

    @RequiresPermission(Manifest.permission.BLUETOOTH_CONNECT)
    override fun onBindViewHolder(p0: BluetoothViewHolder, p1: Int) {
       val tv = p0.itemView.findViewById<TextView>(R.id.tv)
        tv.text = bluetoothDevices[p1].name+":"+bluetoothDevices[p1].address
    }


    fun setData(bluetoothDevices:List<BluetoothDevice>){
        this.bluetoothDevices.clear()
        this.bluetoothDevices.addAll(bluetoothDevices)
        notifyDataSetChanged()
    }

    fun addData(device: BluetoothDevice){
        this.bluetoothDevices.add( device)
        notifyItemInserted(this.bluetoothDevices.size-1)
    }

    inner class BluetoothViewHolder(itemView: View):RecyclerView.ViewHolder(itemView){
        //点击事件
        init {
            itemView.setOnClickListener {
               onItemClick(bluetoothDevices[adapterPosition])
            }
        }
    }
}